package com.rtx.edi.system.login.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.rtx.edi.system.login.service.AuthUserServices;
import com.rtx.exception.RtxWmsException;
import com.rtx.model.dto.response.ResponseModel;
import com.rtx.model.emums.EnumDataType;
import com.rtx.model.emums.ExceptionCodeEnum;
import com.rtx.model.po.entity.system.User;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 登录模块
 *
 * @author Zy
 */
@Api
@RestController
public class LoginController {

    @Autowired
    private AuthUserServices authUserServices;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "login")
    @ResponseBody
    @PostMapping("login")
    public ResponseModel login(@RequestBody User user) throws Exception {

        ResponseModel responseModel = new ResponseModel();
        responseModel.setReturnCode(ResponseModel.SUCCESS_CODE);
        responseModel.setReturnMgr(ResponseModel.SUCCESS_MSG);

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();

        // 已通过身份验证
        boolean authenticated = subject.isAuthenticated();
        if (authenticated) {

            User oldUser = authUserServices.queryUserByUsername(user.getUsername());
            String token = session.getId().toString();
            responseModel.setToken(token);
            responseModel.setData(oldUser);
            if (StrUtil.isBlank(oldUser.getUserLanguage())) {
                responseModel.setUserLanguage(EnumDataType.LANGUAGE_DEFAULT.getValue());
            } else {
                responseModel.setUserLanguage(oldUser.getUserLanguage());
            }
        } else {

            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            try {
                // 登录验证账号信息
                subject.login(usernamePasswordToken);
                User current = authUserServices.queryUserByUsername(usernamePasswordToken.getUsername());

                session.setAttribute(EnumDataType.USER.getValue(), current);
                String key = EnumDataType.WAREHOUSE_IDENTIFICATION.getValue();
                if (session.getAttribute(key) == null) {
                    session.setAttribute(key, EnumDataType.DEFAULT_DATASOURCE_KEY.getValue());
                }
                String token = session.getId().toString();

                // 更新登录日期
                current.setLastlogintime(DateUtil.date());
                authUserServices.updateLastLoginDate(current);

                responseModel.setToken(token);
                responseModel.setData(current);
                if (StrUtil.isBlank(current.getUserLanguage())) {
                    responseModel.setUserLanguage(EnumDataType.LANGUAGE_DEFAULT.getValue());
                } else {
                    responseModel.setUserLanguage(current.getUserLanguage());
                }
            } catch (UnknownAccountException unknown) {
                responseModel.setReturnCode(EnumDataType.RETURN_CODE_400.getValue());
                responseModel.setReturnMgr(ExceptionCodeEnum.EXC_000016.getCode());
            } catch (IncorrectCredentialsException incorrect) {
                responseModel.setReturnCode(EnumDataType.RETURN_CODE_400.getValue());
                responseModel.setReturnMgr(ExceptionCodeEnum.EXC_000017.getCode());
            } catch (LockedAccountException locked) {
                responseModel.setReturnCode(EnumDataType.RETURN_CODE_400.getValue());
                responseModel.setReturnMgr(ExceptionCodeEnum.EXC_000018.getCode());
            } catch (DisabledAccountException disable) {
                responseModel.setReturnCode(EnumDataType.RETURN_CODE_400.getValue());
                responseModel.setReturnMgr(ExceptionCodeEnum.EXC_000019.getCode());
            }catch (RtxWmsException wms) {
            	 responseModel.setReturnCode(wms.getCode());
                 responseModel.setReturnMgr("用户不存在");
			}catch (Exception e) {
				 responseModel.setReturnCode(EnumDataType.RETURN_CODE_400.getValue());
                 responseModel.setReturnMgr(e.getMessage());
			}
        }
        return responseModel;
    }
}
